package com.changgou.order.service.impl;

import com.changgou.goods.feign.SkuFeign;
import com.changgou.goods.feign.SpuFeign;
import com.changgou.goods.pojo.Sku;
import com.changgou.goods.pojo.Spu;
import com.changgou.order.pojo.OrderItem;
import com.changgou.order.service.CartService;
import entity.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @ClassName CartServiceImpl
 * @Description
 * @Author Mr.L
 * @Date 22:43 2019/11/23
 * @Version 2.1
 **/
@Service
public class CartServiceImpl implements CartService {

    @Autowired(required = false)
    private SkuFeign skuFeign;

    @Autowired(required = false)
    private SpuFeign spuFeign;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void add(Integer num, Long id, String username) {
        //删除该商品的购物车数据
        if(num <= 0){
            //如果传入的数量<= 0， 则删除该商品的购物车数据
            redisTemplate.boundHashOps("Cart_ " + username).delete(id);
        }

        //查询sku
        Result<Sku> resultSku = skuFeign.findById(id);
//        Sku sku = skuFeign.findById(id).getData();
        if (resultSku != null){
            //获取sku
            Sku sku = resultSku.getData();
            //获取spu
            Spu spu = spuFeign.findById(sku.getSpuId()).getData();
            //将商品信息存储带购物车对象中
            OrderItem orderItem = goods2OrderItem(sku, spu, num);
            //将购物车保存到redis中
            redisTemplate.boundHashOps("cart_" + username).put(id, orderItem);

        }
    }

    /**
     * 查询购物车列表
     * @param username
     * @return
     */
    @Override
    public List<OrderItem> list(String username) {
        List<OrderItem> list = redisTemplate.boundHashOps("cart_" + username).values();
        return list;
    }

    private OrderItem goods2OrderItem(Sku sku, Spu spu, Integer num) {
        OrderItem orderItem = new OrderItem();
        orderItem.setCategoryId1(spu.getCategory1Id());
        orderItem.setCategoryId2(spu.getCategory2Id());
        orderItem.setCategoryId3(spu.getCategory3Id());
        orderItem.setSpuId(spu.getId());
        orderItem.setSkuId(sku.getId());
        orderItem.setName(sku.getName());           // 商品名称
        orderItem.setPrice(sku.getPrice());         // 商品单价
        orderItem.setNum(num);                      // 购买数量
        orderItem.setMoney(sku.getPrice() * num);   // 总金额
        orderItem.setPayMoney(sku.getPrice() * num);// 实付金额 = 总金额 - 优惠券 - e卡等
        orderItem.setImage(sku.getImage());         // 商品图片
        orderItem.setWeight(sku.getWeight());       // 商品重量
        orderItem.setPostFee(9);                    // 商品运费 = 总金额判断是否超过 99   金牌会员
        orderItem.setIsReturn("0");                 // 商品的退货状态
        return orderItem;

    }
}
